package autocheck

import (
	"fmt"
	"cloud_worm/wormweb/controllers/ctrconfig"
	"time"
	"cloud_worm/util/umodels/mysqldb"
	"cloud_worm/util/umodels/mysqldb/dbmanager"
	"cloud_worm/util/umodels/mysqldb/dbtask"
	"cloud_worm/wormweb/controllers/ctrutil"
	"strings"
	"cloud_worm/util/uid"
	"cloud_worm/wormweb/controllers/ctrsecurity/webtask/fasttask"
	"cloud_worm/wormweb/controllers/ctrinner/taskqueue"
	"github.com/astaxie/beego/logs"
)

type NotifyAutoCheck struct {
	AgentIP 		string
	AgentID 		string
}

func (n *NotifyAutoCheck) Doing()  {
	if err := n.check(n.AgentIP, n.AgentID); err != nil {
		// TODO: 通知操作
	}
	return
}

func (n *NotifyAutoCheck) check(agentIP string, agentID string) error {
	if CheckAutoForOnline == false {
		return nil
	}
	time.Sleep(5 * time.Second)			// 需要等待3s，才能下发任务

	// 处理weapons
	wp := dbtask.Weapon{}
	wps, err := wp.SelectByMode(mysqldb.SelectOffsetZero, mysqldb.SelectLimitAll, mysqldb.StatusValid,
		dbtask.WeaponTaskModeBaseSec, mysqldb.SelectIntAll)
	if err != nil {
		return fmt.Errorf("select weapons error: %s", err.Error())
	}
	var wpsNames []string
	for _, item := range wps {
		wpsNames = append(wpsNames, item.Name)
	}

	// 任务id
	// 准备插入任务
	task := &dbtask.WeaponTask{
		TaskId:      uid.TaskIdProducer().CreateTaskId(),
		TaskOwner:   "CheckAutoEnable",
		TargetType:  ctrutil.TaskForMachine,
		Target:      fmt.Sprintf("指定ip(%s)", agentIP),
		WeaponsName: strings.Join(wpsNames, ","),
		Comment:     "指定ip基础扫描",
		SumCount:    len(wpsNames),
		Created:     time.Now().Unix(),
		Status:      ctrutil.WEAPON_TASK_NO_DO,
	}
	task.Updated = task.Created
	err = task.Insert()
	if err != nil {
		return fmt.Errorf("insert task error: %s", err.Error())
	}

	// 执行任务
	notifyChan := fasttask.WaitTaskFinish(task, len(wps), fasttask.IsNeedTaskAlertDeal(task.WeaponsName))
	for _, wp := range wpsNames {
		taskItem := &fasttask.TaskItem{
			NotifyChan: notifyChan,
			TaskId: task.TaskId,
			WormId: agentID,
			WeaponName: wp,
			Input: "",                              // todo：考虑何时可以设置入参的设计
		}
		taskqueue.FastQueInst().MsgQ.Push(taskItem)
	}

	return nil
}

var CheckAutoForOnline = false

const CheckAutoForOnlineName = "check_auto_for_online"

// 加载配置
func CheckAutoForOnlineLoad() error {
	conf := &dbmanager.WebConfig{Name: CheckAutoForOnlineName}
	if err := conf.Read("name"); err == nil {
		switch conf.Value {
		case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "Y", "y", "ON", "on", "On":
			CheckAutoForOnline = true
		case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "N", "n", "OFF", "off", "Off":
			CheckAutoForOnline = false
		default:
			return fmt.Errorf("config value format error")
		}
	} else {
		return fmt.Errorf("读WolConfig(%s)错误: %s", CheckAutoForOnlineName, err.Error())
	}
	logs.Info(fmt.Sprintf("set %s=%v", CheckAutoForOnlineName, CheckAutoForOnline))

	return nil
}

func init() {
	ctrconfig.RegisterConfigLoad(CheckAutoForOnlineName, CheckAutoForOnlineLoad)

	// 尝试创建该列数据
	conf := &dbmanager.WebConfig{Name: CheckAutoForOnlineName}
	if err := conf.Read("name"); err != nil {
		conf.Commit = "wolagent上线自动检查"
		conf.Type = dbmanager.BoolValue
		conf.Value = "false"
		conf.Created = time.Now().Unix()
		conf.Updated = conf.Created
		conf.Status = mysqldb.StatusValid
		conf.Insert()
	}

	CheckAutoForOnlineLoad()
}
